<?php
session_start();

// 数据库配置
$db_config = [
    'host' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'fastadmin'
];

// 连接数据库
function connectDB($config) {
    try {
        $pdo = new PDO(
            "mysql:host={$config['host']};dbname={$config['database']};charset=utf8mb4",
            $config['username'],
            $config['password'],
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false
            ]
        );
        return $pdo;
    } catch (PDOException $e) {
        die("数据库连接失败: " . $e->getMessage());
    }
}

// 用户登录验证
function authenticateUser($username, $password) {
    global $db_config;
    
    try {
        $pdo = connectDB($db_config);
        
        // 查询用户
        $stmt = $pdo->prepare("SELECT id, username, password, salt, status FROM fa_admin WHERE username = ? AND status = 'normal'");
        $stmt->execute([$username]);
        $user = $stmt->fetch();
        
        if ($user && password_verify($password . $user['salt'], $user['password'])) {
            // 更新最后登录时间
            $updateStmt = $pdo->prepare("UPDATE fa_admin SET logintime = ?, loginip = ? WHERE id = ?");
            $updateStmt->execute([time(), $_SERVER['REMOTE_ADDR'], $user['id']]);
            
            return $user;
        }
        
        return false;
    } catch (PDOException $e) {
        error_log("数据库查询错误: " . $e->getMessage());
        return false;
    }
}

// 生成CSRF令牌
function generateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// 验证CSRF令牌
function validateCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// 处理登录请求
$error_message = '';
$success_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCSRFToken($_POST['csrf_token'] ?? '')) {
        $error_message = '安全令牌验证失败，请刷新页面重试';
    } else {
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        
        if (empty($username) || empty($password)) {
            $error_message = '用户名和密码不能为空';
        } else {
            $user = authenticateUser($username, $password);
            
            if ($user) {
                // 登录成功，设置会话
                $_SESSION['admin_id'] = $user['id'];
                $_SESSION['admin_username'] = $user['username'];
                $_SESSION['admin_login_time'] = time();
                $_SESSION['admin_ip'] = $_SERVER['REMOTE_ADDR'];
                
                // 记录登录日志
                logLogin($user['id'], $username, $_SERVER['REMOTE_ADDR']);
                
                // 跳转到后台首页
                header('Location: admin/index.php');
                exit;
            } else {
                $error_message = '用户名或密码错误';
            }
        }
    }
}

// 记录登录日志
function logLogin($adminId, $username, $ip) {
    global $db_config;
    
    try {
        $pdo = connectDB($db_config);
        $stmt = $pdo->prepare("INSERT INTO fa_admin_log (admin_id, username, title, url, ip, useragent, createtime) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $adminId,
            $username,
            '管理员登录',
            '/login.html',
            $ip,
            $_SERVER['HTTP_USER_AGENT'] ?? '',
            time()
        ]);
    } catch (PDOException $e) {
        error_log("记录登录日志失败: " . $e->getMessage());
    }
}

// 检查是否已登录
if (isset($_SESSION['admin_id'])) {
    header('Location: admin/index.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统 - 登录</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .login-container {
            background: white;
            padding: 40px;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
            animation: fadeInUp 0.6s ease-out;
        }
        
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .login-header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .login-header h1 {
            color: #333;
            font-size: 28px;
            margin-bottom: 10px;
        }
        
        .login-header p {
            color: #666;
            font-size: 14px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }
        
        .form-group input {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }
        
        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .login-btn {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s ease;
        }
        
        .login-btn:hover {
            transform: translateY(-2px);
        }
        
        .login-btn:active {
            transform: translateY(0);
        }
        
        .message {
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
        }
        
        .error {
            background: #fee;
            color: #c33;
            border: 1px solid #fcc;
        }
        
        .success {
            background: #efe;
            color: #3c3;
            border: 1px solid #cfc;
        }
        
        .form-footer {
            text-align: center;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }
        
        .form-footer a {
            color: #667eea;
            text-decoration: none;
            font-size: 14px;
        }
        
        .form-footer a:hover {
            text-decoration: underline;
        }
        
        .captcha-container {
            display: flex;
            gap: 10px;
        }
        
        .captcha-container input {
            flex: 1;
        }
        
        .captcha-image {
            width: 100px;
            height: 44px;
            border: 2px solid #e1e5e9;
            border-radius: 8px;
            cursor: pointer;
            background: #f8f9fa;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            color: #666;
        }
        
        @media (max-width: 480px) {
            .login-container {
                margin: 20px;
                padding: 30px 20px;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-header">
            <h1>后台管理系统</h1>
            <p>请登录您的账户</p>
        </div>
        
        <?php if ($error_message): ?>
            <div class="message error">
                <?php echo htmlspecialchars($error_message); ?>
            </div>
        <?php endif; ?>
        
        <?php if ($success_message): ?>
            <div class="message success">
                <?php echo htmlspecialchars($success_message); ?>
            </div>
        <?php endif; ?>
        
        <form method="POST" action="" id="loginForm">
            <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
            
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" name="username" required 
                       placeholder="请输入用户名" 
                       value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" name="password" required 
                       placeholder="请输入密码">
            </div>
            
            <div class="form-group">
                <label for="captcha">验证码</label>
                <div class="captcha-container">
                    <input type="text" id="captcha" name="captcha" required 
                           placeholder="请输入验证码" maxlength="4">
                    <div class="captcha-image" onclick="refreshCaptcha()">
                        点击刷新
                    </div>
                </div>
            </div>
            
            <button type="submit" class="login-btn">登录</button>
        </form>
        
        <div class="form-footer">
            <a href="#" onclick="forgotPassword()">忘记密码？</a>
            <span style="margin: 0 10px;">|</span>
            <a href="#" onclick="showHelp()">帮助</a>
        </div>
    </div>
    
    <script>
        // 表单验证
        document.getElementById('loginForm').addEventListener('submit', function(e) {
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value;
            const captcha = document.getElementById('captcha').value.trim();
            
            if (!username) {
                e.preventDefault();
                alert('请输入用户名');
                document.getElementById('username').focus();
                return false;
            }
            
            if (!password) {
                e.preventDefault();
                alert('请输入密码');
                document.getElementById('password').focus();
                return false;
            }
            
            if (!captcha) {
                e.preventDefault();
                alert('请输入验证码');
                document.getElementById('captcha').focus();
                return false;
            }
            
            // 显示加载状态
            const btn = document.querySelector('.login-btn');
            btn.textContent = '登录中...';
            btn.disabled = true;
        });
        
        // 刷新验证码
        function refreshCaptcha() {
            const captchaImage = document.querySelector('.captcha-image');
            captchaImage.textContent = Math.random().toString(36).substr(2, 4).toUpperCase();
        }
        
        // 忘记密码
        function forgotPassword() {
            alert('请联系系统管理员重置密码');
        }
        
        // 显示帮助
        function showHelp() {
            alert('登录帮助：\n1. 用户名：输入您的管理员用户名\n2. 密码：输入您的登录密码\n3. 验证码：点击验证码图片刷新');
        }
        
        // 页面加载完成后初始化验证码
        document.addEventListener('DOMContentLoaded', function() {
            refreshCaptcha();
            
            // 回车键提交表单
            document.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    document.getElementById('loginForm').submit();
                }
            });
        });
        
        // 自动聚焦用户名输入框
        document.getElementById('username').focus();
    </script>
</body>
</html>
